package com.example.pei.ithinklearnt.view.activity;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;

import android.graphics.Color;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.pei.ithinklearnt.AppApplication;
import com.example.pei.ithinklearnt.R;
import com.example.pei.ithinklearnt.adapter.CommentAdapter;
import com.example.pei.ithinklearnt.adapter.NineGridTestAdapter;
import com.example.pei.ithinklearnt.bean.AlumniCircle;
import com.example.pei.ithinklearnt.bean.Comment;
import com.example.pei.ithinklearnt.bean.UserInfo;
import com.example.pei.ithinklearnt.listener.QueryUserListener;
import com.example.pei.ithinklearnt.model.UserModel;
import com.example.pei.ithinklearnt.present.DynamicDetailsPresent;
import com.example.pei.ithinklearnt.present.DynamicDetailsPresentImp;
import com.example.pei.ithinklearnt.utils.DialogUtil;
import com.example.pei.ithinklearnt.view.customview.CommentSelectedDialog;
import com.example.pei.ithinklearnt.view.customview.DynamicDetailsHeaderView;
import com.example.pei.ithinklearnt.view.customview.dynamicSelectedDialog;
import com.example.pei.ithinklearnt.view.interfaces.DynamicDetailsInterface;
import com.jaeger.ninegridimageview.NineGridImageView;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;


import java.util.ArrayList;

import cn.bmob.v3.exception.BmobException;

import static com.example.pei.ithinklearnt.utils.BeanOperationUtil.getBean;
import static com.example.pei.ithinklearnt.utils.DialogUtil.CreateVerifyDialog;
import static com.example.pei.ithinklearnt.utils.MyUtils.getDensity;
import static com.example.pei.ithinklearnt.utils.MyUtils.getSendTime;
import static com.example.pei.ithinklearnt.utils.MyUtils.isAllSpace;


//点击进来的动态详情页面
public class DynamicDetails extends AppCompatActivity implements DynamicDetailsInterface,View.OnClickListener ,TextWatcher{

    private DynamicDetailsPresent dynamicDetailsPresent;

    private Button button_add;
    private EditText editText_content;

    private ListView mListView;
    private CommentAdapter mAdapter;
    private ImageView imageView_back;
    private ImageView imageView_threePoint;
    private SmartRefreshLayout mRefreshLayout;
    private dynamicSelectedDialog mDynamicSelectedDialog;
    private CommentSelectedDialog mCommentSelectedDialog;


    private DynamicDetailsHeaderView headerView;

    private Comment comment;  //评论
    private ArrayList<String> photos; //图片

    private AlumniCircle alumniCircle;  //评论的这条动态

    private int  permission;   //当前用户对这条动态的权限  还有一个当前用户对评论的权限，不是这个


    private UserInfo userTo;   //用户回复的人 比如A回复B ，那么这个变量就是B
    private String toc="";


    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dynamic_details);

        dynamicDetailsPresent=new DynamicDetailsPresentImp(this);


        findWidgets();

        headerView = new DynamicDetailsHeaderView(DynamicDetails.this,new NineGridTestAdapter.itemListener(){
            @Override public void onThreePointClick(View v, int position) {}

            @Override
            public void onHeadClick(View v, int position) {

                Bundle bundle = new Bundle();
                bundle.putSerializable("u", alumniCircle.getSender());

                Intent intent = new Intent();
                intent.setClass(getActivity(), UserInfoActivity0.class);
                intent.putExtra(getActivity().getPackageName(), bundle);
                getActivity().startActivity(intent);

            }

            @Override
            public void onItemClick(View view, int position) {
                userTo=alumniCircle.getSender();
                toc="";
                editText_content.setHint("   输入你想评论的内容");
            }

            @Override
            public void onHeartClick(View v, int position) {
                dynamicDetailsPresent.praiseAlumniCircle(AppApplication.getCurrentUser().getUsername(),alumniCircle.getObjectId());
            }

            @Override
            public void onItemLongClick(View view, int position) {
                createDialog();
            }
        });

        Intent intent=getIntent();
        alumniCircle=(AlumniCircle) getBean(this,"alu","1");
        userTo=alumniCircle.getSender();

        permission=intent.getIntExtra("permission",0);
        photos=(ArrayList<String>)alumniCircle.getphotos();  //list转arrayList
        int commentNum=alumniCircle.getCommentNumber();
        int praiseNum=alumniCircle.getPraiseNumber();

        dynamicDetailsPresent.queryComments(alumniCircle);

        //设置发送者头像
        headerView.setSenderHead(alumniCircle.getSender().getHeadFileUrl());
        //设置发送者姓名
        headerView.setSenderName(alumniCircle.getSender().getNickName());
        //设置发送的文字内容
        headerView.setSendContent(alumniCircle.getContent());
        //设置发送者性别
        headerView.setSenderSex(alumniCircle.getSender().getSex());
        //设置发送时间
        headerView.setSendTime(getSendTime(alumniCircle.getCreatedAt()));
        //设置评论数量
        headerView.setCommentNum(commentNum);
        //设置点赞数量
        headerView.setPraiseNum(praiseNum);
        //设置当前动态的图片数据
        headerView.setImagesData(photos,NineGridImageView.STYLE_GRID);
        //设置当前用户是否点赞过这个动态
        headerView.setIsPraised(intent.getIntExtra("isPraised",0));


        dynamicDetailsPresent.initDynamicCommentAndPraiseNum(commentNum,praiseNum);
        mListView.addHeaderView(headerView);
        mAdapter=new CommentAdapter(DynamicDetails.this,new ArrayList<Comment>());
        mListView.setAdapter(mAdapter);

        //单击评论，则回复这条评论
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(position!=0) {   //不是主体，是评论的话

                    //如果点击的不是自己的评论
                    if(!mAdapter.getItem(position-1).getUserFrom().getObjectId().equals(AppApplication.getCurrentUser().getObjectId())){
                        //打开输入法
                        InputMethodManager imm = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                        //设置hint
                        editText_content.setHint("回复 " + mAdapter.getItem(position-1).getUserFrom().getNickName());
                        userTo=mAdapter.getItem(position-1).getUserFrom();
                        toc=mAdapter.getItem(position-1).getContent();
                    }
                }
            }
        });
        //长按评论 ，可以选择复制、评论或删除评论
        mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view,final int i, long l) {
                if(i==0){  //动态主体，不是评论
                    return false;
                }
                View vieww = getLayoutInflater().inflate(R.layout.comment_selected_dialog, null);
                int permission=getPermission(i);
                mCommentSelectedDialog=new CommentSelectedDialog(DynamicDetails.this,R.style.transparentFrameWindowStyle,permission,new CommentSelectedDialog.CommentSelectedDialogListener(){
                    @Override
                    public void onClick(View v) {
                        mCommentSelectedDialog.dismiss();
                        switch (v.getId()){
                            case R.id.btn_reply:
                                //打开输入法
                                getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
                                InputMethodManager imm = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                                imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                                //设置hint
                                editText_content.setHint("回复 " + mAdapter.getItem(i-1).getUserFrom().getNickName());
                                //to=mAdapter.getItem(i-1).getUserFrom().getUsername();
                                toc=mAdapter.getItem(i-1).getContent();
                                break;
                            case R.id.btn_copy:
                                getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
                                ClipboardManager cm = (ClipboardManager) DynamicDetails.this.getSystemService(Context.CLIPBOARD_SERVICE);
                                ClipData mClipData = ClipData.newPlainText("Label", mAdapter.getItem(i-1).getContent());
                                assert cm != null;
                                cm.setPrimaryClip(mClipData);
                                Toast.makeText(getActivity(),"已经复制好啦!",Toast.LENGTH_SHORT).show();
                                break;
                            case R.id.btn_del:
                                getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
                                dynamicDetailsPresent.deleteComment(mAdapter.getItem(i-1).getObjectId(),mAdapter.getItem(i-1).getDynamic().getObjectId(),i);
                                break;
                        }

                    }
                });
                mCommentSelectedDialog.setContentView(vieww, new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT));
                Window window = mCommentSelectedDialog.getWindow();

                assert window != null;
                WindowManager.LayoutParams wl = window.getAttributes();
                wl.x = 0;
                // wl.y = (getWindowManager().getDefaultDisplay().getHeight());
                wl.gravity = Gravity.CENTER;
                // 以下这两句是为了保证按钮可以水平满屏
                wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
                wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                // 设置显示位置
                mCommentSelectedDialog.onWindowAttributesChanged(wl);
                // 设置点击外围解散
                mCommentSelectedDialog.setCanceledOnTouchOutside(true);
                mCommentSelectedDialog.show();

                return false;
            }
        });
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override public void onScroll(AbsListView absListView, int i, int i1, int i2) {}
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
              //  to="123456789";
                userTo=alumniCircle.getSender();
                toc="";
                editText_content.setHint("   输入你想评论的内容");
            }
        });
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        //这个函数用于重新设置Like的位置
        int density=getDensity(this);    //获取屏幕密度
        int[] location = new int[2];
        headerView.getTextView_praiseNum().getLocationOnScreen(location);
        int x = location[0];
        int y = location[1];                        //获取在屏幕上的绝对位置y坐标
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(headerView.getLikeViewLayout().getLayoutParams().width,y-50*density);   // 设置控件的宽度和高度，这个50是标题栏的dp
        params.gravity = Gravity.RIGHT;
        params.setMargins(0, 0, 0*density, 22*density);   //设置边缘距离  0,24是xml文件中的值
        headerView.getLikeViewLayout().setLayoutParams(params);
        headerView.getLikeViewLayout().setGravity(Gravity.CENTER|Gravity.BOTTOM);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_add:
                if(isAllSpace(editText_content.getText().toString())){
                    break;   //为空 退出
                }
                getComment();
                comment.setBcontent(toc);
                //comment.setToID(to);
                comment.setUserTo(userTo);
                comment.setUserFrom(AppApplication.getCurrentUser());   //设置当前用户为评论者
                dynamicDetailsPresent.sendComment(comment);

                //to="123456789";         //这两个字符串代表着评论是直接回复动态发送者的
                userTo=alumniCircle.getSender();
                toc="";
                editText_content.setHint("   输入你想评论的内容");

                break;
            case R.id.iv_back:
                setResult(RESULT_OK);
                finish();
                break;
            case R.id.threepoint:
                createDialog();
                break;
        }
    }

    @Override
    public void setPraised() {
        headerView.setIsPraised(1);
    }

    @Override
    public void onBackPressed()
    {
        setResult(RESULT_OK);
        super.onBackPressed();
    }

    @Override
    public Activity getActivity() {
        return DynamicDetails.this;
    }

    @Override
    public CommentAdapter getAdapter() {
        return mAdapter;
    }

    @Override
    public void clearEditText() {
        editText_content.setText("");
    }

    @Override
    public void setCommentNumer(int num) {
        headerView.setCommentNum(num);
    }

    @Override
    public void setPraiseNumber(int num) {
        headerView.setPraiseNum(num);
    }

    @Override
    public void btn_sendCommentClickable(boolean enable) {
        button_add.setClickable(enable);
    }

    @Override
    public Comment getComment() {
        comment=new Comment();

        comment.setDynamic(alumniCircle);                                              //设置评论的是哪一个动态
        comment.setContent(editText_content.getText().toString());                 //设置评论内容
        return comment;
    }

    @Override public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
    @Override public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
    @Override
    public void afterTextChanged(Editable editable) {
        if(!isAllSpace(editText_content.getText().toString())){
            button_add.setTextColor(Color.parseColor("#2fe176"));
            button_add.setClickable(true);
        }else{
            button_add.setTextColor(Color.parseColor("#999999"));
            button_add.setClickable(false);
        }
    }

    private void findWidgets(){
        mListView=findViewById(R.id.list_item);
        button_add=findViewById(R.id.btn_add);
        button_add.setOnClickListener(this);
        editText_content=findViewById(R.id.et_content);
     //   editText_content.setInputType(InputType.TYPE_NULL);
        editText_content.requestFocus();//获取焦点 光标出现
       // editText_content.setInputType(InputType.);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        editText_content.addTextChangedListener(this);
        imageView_back=findViewById(R.id.iv_back);
        imageView_back.setOnClickListener(this);
        mRefreshLayout=findViewById(R.id.refreshLayout);
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                dynamicDetailsPresent.queryComments(alumniCircle);
                dynamicDetailsPresent.queryHeader(alumniCircle.getObjectId());
            }
        });
        imageView_threePoint=findViewById(R.id.threepoint);
        imageView_threePoint.setOnClickListener(this);
    }

    @Override
    public void refreshFinish(boolean success) {
        mRefreshLayout.finishRefresh(success);
    }



    private void createDialog(){
        View vieww = getLayoutInflater().inflate(R.layout.dynamic_selected_dialog, null);
        mDynamicSelectedDialog=new dynamicSelectedDialog(DynamicDetails.this, R.style.transparentFrameWindowStyle,permission, new dynamicSelectedDialog.Listener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()){
                    case R.id.btn_copy:
                        ClipboardManager cm = (ClipboardManager)DynamicDetails.this.getSystemService(Context.CLIPBOARD_SERVICE);
                        ClipData mClipData = ClipData.newPlainText("Label", alumniCircle.getContent());
                        assert cm != null;
                        cm.setPrimaryClip(mClipData);
                        Toast.makeText(getActivity(),"已经复制好啦!",Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.btn_shield:
                        // 屏蔽某条动态
                        dynamicDetailsPresent.shieldAlumniCircle(AppApplication.getCurrentUser().getUsername(),alumniCircle.getObjectId());
                        break;
                    case R.id.btn_del:
                        CreateVerifyDialog(DynamicDetails.this, "确认删除这条主题吗", new DialogUtil.CreateVerifyDialogListener() {
                            @Override public void cancel() {}
                            @Override
                            public void confirm() {
                                //删除数据库里的内容
                                dynamicDetailsPresent.deleteAlumniCircle(alumniCircle,photos);
                            }
                        });
                        break;
                }
                mDynamicSelectedDialog.dismiss();
            }
        });
        mDynamicSelectedDialog.setContentView(vieww, new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT));
        Window window = mDynamicSelectedDialog.getWindow();
        // 设置显示动画
        //   window.setWindowAnimations(R.style.main_menu_animstyle);
        assert window != null;
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        // wl.y = (getWindowManager().getDefaultDisplay().getHeight());
        wl.gravity = Gravity.CENTER;
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // 设置显示位置
        mDynamicSelectedDialog.onWindowAttributesChanged(wl);
        // 设置点击外围解散
        mDynamicSelectedDialog.setCanceledOnTouchOutside(true);
        mDynamicSelectedDialog.show();
    }

    //返回为所选的item创建dialog时的权限
    private int getPermission(int position){
        int permission=0;
        if(AppApplication.getCurrentUser()!=null){
            String username=AppApplication.getCurrentUser().getUsername();

            if(mAdapter.getItem(position-1).getUserFrom().getUsername().equals(username)){
                //是自己发送的
                permission=1;
            } else{
                //bu 是自己发送的
                permission=0;
            }
        }
        return permission;
    }

}
